﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LogisticDatabase.Models;
using LogisticDatabase.Data;

namespace LogisticDatabase
{
    public class CityDataAccess : IDataAccess<City>
    {
       
        public City getCityById(int id)
        {
            City city = null;
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                var c = ctx.tblCity.FirstOrDefault(t => t.CityID == id);
             
                if(c!=null)
                {
                    city = new City { Id = id, Name = c.CityName, Country = c.CityCountry };
                }
                
            }
            return city;

        }

        public List<City> listAll()
        {
            List<City> cities = new List<City>();
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                cities = ctx.tblCity.Select(t => new City { Id = t.CityID, Name = t.CityName, Country = t.CityCountry }).ToList();
        
            }
            return cities;

        }
        public void edit(City city)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                var c = ctx.tblCity.FirstOrDefault(t => t.CityID == city.Id);
                if (c != null)
                {
                    c.CityName = city.Name;
                    c.CityCountry = city.Country;

                    ctx.SaveChanges();
                }


              
            }
        }
        public void add(City city)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                tblCity tc = new tblCity();

                tc.CityName = city.Name;
                tc.CityCountry = city.Country;

                ctx.tblCity.Add(tc);

                ctx.SaveChanges();
            }
        }
        
        public void delete(City city)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                var c = ctx.tblCity.FirstOrDefault(t => t.CityID == city.Id);
                if (c != null)
                {
                    ctx.tblCity.Remove(c);
                    ctx.SaveChanges();
                }
            }

        }
    }
}
